package com.example.searchcenter.center;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.example.searchcenter.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import android.os.Bundle;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.view.Display;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;

/***
 * 
 * @author NguyenTrung A class function is Find direction from STARTADDRESS to
 *         ENDADDRESS
 * 
 */
public class MapsDirection extends FragmentActivity {

	private LatLng STARTADDRESS = null;
	private LatLng ENDADDRESS = new LatLng(
			Double.parseDouble(DetailsCenter.place_lat),
			Double.parseDouble(DetailsCenter.place_long));

	private GoogleMap map;
	private SupportMapFragment fragment;
	private LatLngBounds latlngBounds;
	private Polyline newPolyline;
	// private boolean isTravelingToParis = true;
	private int width, height;
	// GPSTracker class
	GPSTracker gps;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.maps_direction);

		// create map
		getSreenDimanstions();
		fragment = ((SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map));
		map = fragment.getMap();
		//
		// get current location
		// create class object
		gps = new GPSTracker(MapsDirection.this);
		// check if GPS enabled
		if (gps.canGetLocation) {
			STARTADDRESS = new LatLng(gps.getLatitude(), gps.getLongitude());
			Toast.makeText(getApplicationContext(),
					String.valueOf(gps.getLatitude()), Toast.LENGTH_LONG)
					.show();
		} else {
			// can't get location
			// GPS or Network is not enabled
			// Ask user to enable GPS/network in settings
			gps.showSettingsAlert();
		}
		// get and set the autocomplete
		AutoCompleteTextView from = (AutoCompleteTextView) findViewById(R.id.from);
		AutoCompleteTextView to = (AutoCompleteTextView) findViewById(R.id.to);
		// Set text for autocompletes
		from.setText("Vị trí hiện tại");
		to.setText(DetailsCenter.name_center);
		// Set Adapter for two autocompletes

		from.setAdapter(new PlacesAutoCompleteAdapter(this,
				android.R.layout.simple_dropdown_item_1line));
		to.setAdapter(new PlacesAutoCompleteAdapter(this,
				android.R.layout.simple_dropdown_item_1line));

		// Get button findDirection from xml
		Button findDirection = (Button) findViewById(R.id.bNavigation);
		// Set event click on findDirection button.
		findDirection.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				findDirections(STARTADDRESS.latitude, STARTADDRESS.longitude,
						ENDADDRESS.latitude, ENDADDRESS.longitude,
						GMapV2Direction.MODE_DRIVING);

			}
		});

	}

	@Override
	protected void onResume() {

		super.onResume();
		latlngBounds = createLatLngBoundsObject(STARTADDRESS, ENDADDRESS);
		map.moveCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width,
				height, 150));
		// Create marker
		MarkerOptions marker_start = new MarkerOptions().position(STARTADDRESS)
				.title("Vị trí hiện tại");
		marker_start.icon(BitmapDescriptorFactory
				.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));

		MarkerOptions marker_end = new MarkerOptions().position(ENDADDRESS)
				.title(DetailsCenter.name_center);
		marker_end.icon(BitmapDescriptorFactory
				.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

		// Add marker
		Marker location_end = map.addMarker(marker_end);
		Marker location_start = map.addMarker(marker_start);
		location_end.showInfoWindow();
		location_start.showInfoWindow();

	}

	public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
		PolylineOptions rectLine = new PolylineOptions().width(5).color(
				Color.RED);

		for (int i = 0; i < directionPoints.size(); i++) {
			rectLine.add(directionPoints.get(i));
		}
		if (newPolyline != null) {
			newPolyline.remove();
		}
		newPolyline = map.addPolyline(rectLine);

		latlngBounds = createLatLngBoundsObject(STARTADDRESS, ENDADDRESS);
		map.moveCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width,
				height, 150));

	}

	@SuppressWarnings("deprecation")
	private void getSreenDimanstions() {
		Display display = getWindowManager().getDefaultDisplay();
		width = display.getWidth();
		height = display.getHeight();
	}

	private LatLngBounds createLatLngBoundsObject(LatLng firstLocation,
			LatLng secondLocation) {
		if (firstLocation != null && secondLocation != null) {
			LatLngBounds.Builder builder = new LatLngBounds.Builder();
			builder.include(firstLocation).include(secondLocation);

			return builder.build();
		}
		return null;
	}

	public void findDirections(double fromPositionDoubleLat,
			double fromPositionDoubleLong, double toPositionDoubleLat,
			double toPositionDoubleLong, String mode) {
		Map<String, String> map = new HashMap<String, String>();
		map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT,
				String.valueOf(fromPositionDoubleLat));
		map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG,
				String.valueOf(fromPositionDoubleLong));
		map.put(GetDirectionsAsyncTask.DESTINATION_LAT,
				String.valueOf(toPositionDoubleLat));
		map.put(GetDirectionsAsyncTask.DESTINATION_LONG,
				String.valueOf(toPositionDoubleLong));
		map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);

		GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
		asyncTask.execute(map);
	}
}
